<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <page-tools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <template #right>
          <el-button type="primary" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="warning" @click="handleDownload">excel导出</el-button>
          <el-button type="danger" @click="showDialog=true">添加员工</el-button>
        </template>
      </page-tools>
      <!-- 员工表格 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <img
                v-imageerr="defaultImg"
                :src="row.staffPhoto || defaultImg"
                style="width:70px;height:70px;border-radius:50%;"
                @click="showEwm(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" :formatter="formatEmployment" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | dateFormat() }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button :disabled="!checkPermission('POINT_USER_LOOK')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button v-if="checkPermission('POINT_USER_DEL')" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pagesize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增员工弹出框组件 -->
      <AddEmployee :show-dialog.sync="showDialog" />

      <!-- 分配角色弹出框组件 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

      <!-- 二维码弹层 -->
      <el-dialog title="二维码" :visible.sync="showEwmDialog" width="300px">
        <el-row type="flex" justify="center">
          <canvas ref="code" />
        </el-row>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { reqGetEmployeeList } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'

// 导入默认图片
import defaultImg from '@/assets/common/head.jpg'

import qrCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      pagesize: 10,
      employeeList: [],
      total: 0,

      showDialog: false, // 控制新增员工组件显示与隐藏

      defaultImg, // 默认头像

      showEwmDialog: false, // 控制二维码显示与隐藏

      showRoleDialog: false, // 控制分配置角色组件显示与隐藏

      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {

    // 检查员工按钮权限
    checkPermission(type) {
      const points = this.$store.getters.roles.points

      if (points.includes(type)) {
        return true
      } else {
        return false
      }
    },

    // 获取员工列表
    async getEmployeeList() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.pagesize)
      this.employeeList = rows
      this.total = total
    },
    // 处理分页的页码值改变
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    // row:行
    // column:列
    // cellValue: 单元格值
    // index:索引
    formatEmployment(row, column, cellValue, index) {
      const { hireType } = employeeEnum

      // 根据id找对象
      const result = hireType.find(item => item.id === parseInt(cellValue))

      return result ? result.value : '未知'
    },

    // 处理员工批量导出
    async handleDownload() {
      // 表头
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      //                 [['姓名', '主要信息', '    ', '        ', '       ', '    ', '部门']]
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 表格数据
      // 1.获取"所有"员工数据 小技巧:total
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      // 最终的结构:[[],[],...]=
      const newArr = [] // 外层的大数组
      rows.forEach(item => {
        const arr = []
        headersArr.forEach(value => {
          const englishKey = headersRelations[value]

          if (englishKey === 'formOfEmployment') {
            const obj = employeeEnum.hireType.find(v => v.id === item[englishKey])
            const res = obj ? obj.value : '未知'
            arr.push(res)
          } else {
            arr.push(item[englishKey])
          }
        })
        newArr.push(arr)
      })

      // webpack资源加载
      // 复杂表头
      // multiHeader:[[]]
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      import('@/vendor/Export2Excel').then(excel => {
        // 实现excel导出
        excel.export_json_to_excel({
          multiHeader: multiHeader,
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          header: headersArr, // 表头
          data: newArr, // 数据 二维数组
          filename: '员工信息表', // 表名称
          autoWidth: true, // 宽度自适应
          bookType: 'xlsx' // 文件扩展名
        })
      })
    },

    // 二维码
    showEwm(url) {
      if (!url) return
      this.showEwmDialog = true
      // el-dialog弹出框中的内容(标签或组件)是懒渲染(异步)

      // 将url地址转换为二维码 qrcode
      // qrCode.toCanvas(dom,url) //dom => canvas
      this.$nextTick(() => {
        qrCode.toCanvas(this.$refs.code, url)
      })
    },

    // 分配角色
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
